/*
 *    Copyright 2009-2022 the original author or authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package org.apache.ibatis.builder.xml;

import java.io.InputStream;
import java.io.Reader;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.ibatis.builder.BaseBuilder;
import org.apache.ibatis.builder.BuilderException;
import org.apache.ibatis.datasource.DataSourceFactory;
import org.apache.ibatis.executor.ErrorContext;
import org.apache.ibatis.executor.loader.ProxyFactory;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.io.VFS;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.mapping.DatabaseIdProvider;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.parsing.XNode;
import org.apache.ibatis.parsing.XPathParser;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.reflection.DefaultReflectorFactory;
import org.apache.ibatis.reflection.MetaClass;
import org.apache.ibatis.reflection.ReflectorFactory;
import org.apache.ibatis.reflection.factory.ObjectFactory;
import org.apache.ibatis.reflection.wrapper.ObjectWrapperFactory;
import org.apache.ibatis.session.AutoMappingBehavior;
import org.apache.ibatis.session.AutoMappingUnknownColumnBehavior;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.LocalCacheScope;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.type.JdbcType;

/**
 * @author Clinton Begin
 * @author Kazuki Shimizu
 */
public class XMLConfigBuilder extends BaseBuilder {

  // 标识是否已经解析过mybatis-config.xml文件
  private boolean parsed;
  // xml解析器
  private final XPathParser parser;
  // <enviroment>标签的内容
  private String environment;
  // 负责创建和缓存Reflective对象
  private final ReflectorFactory localReflectorFactory = new DefaultReflectorFactory();

  public XMLConfigBuilder(Reader reader) {
    this(reader, null, null);
  }

  public XMLConfigBuilder(Reader reader, String environment) {
    this(reader, environment, null);
  }

  public XMLConfigBuilder(Reader reader, String environment, Properties props) {
    this(new XPathParser(reader, true, props, new XMLMapperEntityResolver()), environment, props);
  }

  public XMLConfigBuilder(InputStream inputStream) {
    this(inputStream, null, null);
  }

  public XMLConfigBuilder(InputStream inputStream, String environment) {
    this(inputStream, environment, null);
  }

  public XMLConfigBuilder(InputStream inputStream, String environment, Properties props) {
    // 将生成的doc节点树保存到xpathparser对象中
    this(new XPathParser(inputStream, true, props, new XMLMapperEntityResolver()), environment, props);
  }

  private XMLConfigBuilder(XPathParser parser, String environment, Properties props) {
    // 创建配置对象
    super(new Configuration());
    ErrorContext.instance().resource("SQL Mapper Configuration");
    this.configuration.setVariables(props);
    // 标记为还没解析过
    this.parsed = false;
    this.environment = environment;
    // 设置xpath解析器
    this.parser = parser;
  }

  public Configuration parse() {
    // 如果已经解析过mybatis-config.xml文件了那就抛出异常，不允许重复解析
    if (parsed) {
      //
      throw new BuilderException("Each XMLConfigBuilder can only be used once.");
    }
    // 如果还没解析过，那就标志为已经解析过
    parsed = true;
    // 在mybatis-config.xml文件中寻找configuration节点，并开始解析。正式解析xml文件
    parseConfiguration(parser.evalNode("/configuration"));
    return configuration;
  }

  private void parseConfiguration(XNode root) {
    try {
      // issue #117 read properties first
      // issue 117 先读属性
      // 解析properties节点
      // <properties resource="db.properties"/>
      // 将properties节点对应的资源保存到xparser和configuration对象的variables属性中
      propertiesElement(root.evalNode("properties"));

      // 解析settings节点
      //  <settings>
      //      <setting name="cacheEnabled" value="true"/>
      //  </settings>
      // 获取settings标签的配置信息。
      // 这一步还没有将设置保存到configuration对象中
      Properties settings = settingsAsProperties(root.evalNode("settings"));
      // 加载一些用户自定义的vfs类。不理解
      loadCustomVfs(settings);
      // 加载用户自定义的log类
      loadCustomLogImpl(settings);

      // 解析typeAliases节点.
      // <typeAliases>
      //     <package name="com.iting.bean"/>
      // </typeAliases>
      // 加载类型的别名，以便于不需要每次都使用全限定类名
      typeAliasesElement(root.evalNode("typeAliases"));

      // 解析plugins节点
      // <plugins>
      //     <plugin interceptor="com.github.pagehelper.PageInterceptor"/>
      // </plugins>
      // 将所需的插件实例化并保存
      pluginElement(root.evalNode("plugins"));

      // 解析objectFactory节点
      // 将所需的objectFactory实例化并保存
      objectFactoryElement(root.evalNode("objectFactory"));

      // 解析objectWrapperFactory节点
      // 将所需的objectWrapperFactory实例化并保存
      objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));

      // 解析reflectorFactory节点
      // 将所需的reflectorFactory实例化并保存
      reflectorFactoryElement(root.evalNode("reflectorFactory"));
      // 将上面对settings节点的解析结果设置到configuration对象中。如果settings标签没有设置值，就使用默认值
      settingsElement(settings);

      // read it after objectFactory and objectWrapperFactory issue #631
      // 在 objectFactory 和 objectWrapperFactory 问题 631 之后阅读它
      // 解析environments节点
      // <environments default="development">
      //     <environment id="development">
      //         <transactionManager type="JDBC"/>
      //         <dataSource type="POOLED">
      //             <property name="driver" value="${jdbc.driver}"/>
      //             <property name="url" value="${jdbc.url}"/>
      //             <property name="username" value="${jdbc.username}"/>
      //             <property name="password" value="${jdbc.password}"/>
      //         </dataSource>
      //     </environment>
      // </environments>
      environmentsElement(root.evalNode("environments"));

      // 解析databaseIdProvider节点
      // 数据库id提供者。并手动设置数据库的id
      // mybatis可以根据不同的数据库id，使Mapper接口的同一个方法执行不同的SQL语句
      databaseIdProviderElement(root.evalNode("databaseIdProvider"));

      // 解析typeHandlers节点
      // 处理类型处理器
      typeHandlerElement(root.evalNode("typeHandlers"));

      // 解析mappers节点
      // <mappers>
      //     <package name="com.iting.dao"/>
      // </mappers>
      mapperElement(root.evalNode("mappers"));

    } catch (Exception e) {
      throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
    }
  }

  private Properties settingsAsProperties(XNode context) {
    // 如果没有setting标签，直接返回一个空的集合
    if (context == null) {
      return new Properties();
    }
    // 获取子节点setting的name和value
    Properties props = context.getChildrenAsProperties();
    // Check that all settings are known to the configuration class
    // 检查配置类是否支持所有设置
    // 这个类会持有配置类Class对象的信息
    MetaClass metaConfig = MetaClass.forClass(Configuration.class, localReflectorFactory);
    for (Object key : props.keySet()) {
      // 如果setting标签中配置了某个配置，但是configuration类中没有对应的set方法，则抛出异常
      if (!metaConfig.hasSetter(String.valueOf(key))) {
        throw new BuilderException("The setting " + key + " is not known.  Make sure you spelled it correctly (case sensitive).");
      }
    }
    return props;
  }

  private void loadCustomVfs(Properties props) throws ClassNotFoundException {
    String value = props.getProperty("vfsImpl");
    if (value != null) {
      // 以逗号分割
      String[] clazzes = value.split(",");
      for (String clazz : clazzes) {
        if (!clazz.isEmpty()) {
          @SuppressWarnings("unchecked")
          Class<? extends VFS> vfsImpl = (Class<? extends VFS>)Resources.classForName(clazz);
          configuration.setVfsImpl(vfsImpl);
        }
      }
    }
  }

  private void loadCustomLogImpl(Properties props) {
    Class<? extends Log> logImpl = resolveClass(props.getProperty("logImpl"));
    configuration.setLogImpl(logImpl);
  }

  private void typeAliasesElement(XNode parent) {
    if (parent != null) {
      // 有配置别名才进行解析
      for (XNode child : parent.getChildren()) {
        // 允许多个子标签
        // 如果是以package标签配置的别名
        if ("package".equals(child.getName())) {
          // 获取package标签的name属性
          String typeAliasPackage = child.getStringAttribute("name");
          // 想configuration对象的别名注册表中注册别名
          configuration.getTypeAliasRegistry().registerAliases(typeAliasPackage);
          // 如果不是以package标签配置的别名
        } else {
          // 获取子标签typeAlias的alias属性
          String alias = child.getStringAttribute("alias");
          // 获取子标签的type属性
          String type = child.getStringAttribute("type");
          try {
            // 尝试通过名称加载类
            Class<?> clazz = Resources.classForName(type);
            if (alias == null) {
              // 如果没有指定别名，默认已类的简单类名作为别名
              typeAliasRegistry.registerAlias(clazz);
            } else {
              // 如果指定了别名，就以指定的名称作为别名
              typeAliasRegistry.registerAlias(alias, clazz);
            }
          } catch (ClassNotFoundException e) {
            throw new BuilderException("Error registering typeAlias for '" + alias + "'. Cause: " + e, e);
          }
        }
      }
    }
  }

  private void pluginElement(XNode parent) throws Exception {
    if (parent != null) {
      // 获取子节点plugin
      for (XNode child : parent.getChildren()) {
        // 获取子节点的interceptor属性
        String interceptor = child.getStringAttribute("interceptor");
        // 获取plugin节点的所有子节点的name和value属性
        Properties properties = child.getChildrenAsProperties();
        // 通过反射实例化这个拦截器
        Interceptor interceptorInstance = (Interceptor) resolveClass(interceptor).getDeclaredConstructor().newInstance();
        // 为这个拦截器设置属性值
        interceptorInstance.setProperties(properties);
        // 将插件保存到插件链中
        configuration.addInterceptor(interceptorInstance);
      }
    }
  }

  private void objectFactoryElement(XNode context) throws Exception {
    // 过程和对插件标签的处理是一样的
    if (context != null) {
      // 获取节点的type属性
      String type = context.getStringAttribute("type");
      Properties properties = context.getChildrenAsProperties();
      ObjectFactory factory = (ObjectFactory) resolveClass(type).getDeclaredConstructor().newInstance();
      factory.setProperties(properties);
      configuration.setObjectFactory(factory);
    }
  }

  private void objectWrapperFactoryElement(XNode context) throws Exception {
    if (context != null) {
      String type = context.getStringAttribute("type");
      ObjectWrapperFactory factory = (ObjectWrapperFactory) resolveClass(type).getDeclaredConstructor().newInstance();
      configuration.setObjectWrapperFactory(factory);
    }
  }

  private void reflectorFactoryElement(XNode context) throws Exception {
    if (context != null) {
      String type = context.getStringAttribute("type");
      ReflectorFactory factory = (ReflectorFactory) resolveClass(type).getDeclaredConstructor().newInstance();
      configuration.setReflectorFactory(factory);
    }
  }

  private void propertiesElement(XNode context) throws Exception {
    if (context != null) {
      // 获取子节点的值
      Properties defaults = context.getChildrenAsProperties();
      // 获取resource属性
      String resource = context.getStringAttribute("resource");
      // 获取url属性
      String url = context.getStringAttribute("url");
      // 如果两个属性都有，报错。Resource和url中只能设置一个，但是子节点property可以有多个，且可以和URL或者Resource同时存在
      if (resource != null && url != null) {
        throw new BuilderException("The properties element cannot specify both a URL and a resource based property file reference.  Please specify one or the other.");
      }
      // 如果设置的是resource属性
      if (resource != null) {
        // 解析导入的配置文件中的内容，并保存
        defaults.putAll(Resources.getResourceAsProperties(resource));
        // 如果设置的是url属性
      } else if (url != null) {
        // 这一步会读取db.propertoes文件中的内容。将子节点的内容和当前节点的内容合并
        defaults.putAll(Resources.getUrlAsProperties(url));
      }
      // 尝试获取configuration对象中原有的的变量
      Properties vars = configuration.getVariables();
      if (vars != null) {
        // 如果有，也一起保存到这个集合中
        defaults.putAll(vars);
      }
      // 保存到parser对象的variables属性中
      parser.setVariables(defaults);
      // 保存到configuration对象的variables属性中
      configuration.setVariables(defaults);
    }
  }

  private void settingsElement(Properties props) {
    // props.getProperty("autoMappingBehavior", "PARTIAL")) 如果prop中有，则使用prop中的值，否则使用第二个参数标志的默认值
    configuration.setAutoMappingBehavior(AutoMappingBehavior.valueOf(props.getProperty("autoMappingBehavior", "PARTIAL")));
    configuration.setAutoMappingUnknownColumnBehavior(AutoMappingUnknownColumnBehavior.valueOf(props.getProperty("autoMappingUnknownColumnBehavior", "NONE")));
    configuration.setCacheEnabled(booleanValueOf(props.getProperty("cacheEnabled"), true));
    configuration.setProxyFactory((ProxyFactory) createInstance(props.getProperty("proxyFactory")));
    configuration.setLazyLoadingEnabled(booleanValueOf(props.getProperty("lazyLoadingEnabled"), false));
    configuration.setAggressiveLazyLoading(booleanValueOf(props.getProperty("aggressiveLazyLoading"), false));
    configuration.setMultipleResultSetsEnabled(booleanValueOf(props.getProperty("multipleResultSetsEnabled"), true));
    configuration.setUseColumnLabel(booleanValueOf(props.getProperty("useColumnLabel"), true));
    configuration.setUseGeneratedKeys(booleanValueOf(props.getProperty("useGeneratedKeys"), false));
    configuration.setDefaultExecutorType(ExecutorType.valueOf(props.getProperty("defaultExecutorType", "SIMPLE")));
    configuration.setDefaultStatementTimeout(integerValueOf(props.getProperty("defaultStatementTimeout"), null));
    configuration.setDefaultFetchSize(integerValueOf(props.getProperty("defaultFetchSize"), null));
    configuration.setDefaultResultSetType(resolveResultSetType(props.getProperty("defaultResultSetType")));
    configuration.setMapUnderscoreToCamelCase(booleanValueOf(props.getProperty("mapUnderscoreToCamelCase"), false));
    configuration.setSafeRowBoundsEnabled(booleanValueOf(props.getProperty("safeRowBoundsEnabled"), false));
    configuration.setLocalCacheScope(LocalCacheScope.valueOf(props.getProperty("localCacheScope", "SESSION")));
    configuration.setJdbcTypeForNull(JdbcType.valueOf(props.getProperty("jdbcTypeForNull", "OTHER")));
    configuration.setLazyLoadTriggerMethods(stringSetValueOf(props.getProperty("lazyLoadTriggerMethods"), "equals,clone,hashCode,toString"));
    configuration.setSafeResultHandlerEnabled(booleanValueOf(props.getProperty("safeResultHandlerEnabled"), true));
    configuration.setDefaultScriptingLanguage(resolveClass(props.getProperty("defaultScriptingLanguage")));
    configuration.setDefaultEnumTypeHandler(resolveClass(props.getProperty("defaultEnumTypeHandler")));
    configuration.setCallSettersOnNulls(booleanValueOf(props.getProperty("callSettersOnNulls"), false));
    configuration.setUseActualParamName(booleanValueOf(props.getProperty("useActualParamName"), true));
    configuration.setReturnInstanceForEmptyRow(booleanValueOf(props.getProperty("returnInstanceForEmptyRow"), false));
    configuration.setLogPrefix(props.getProperty("logPrefix"));
    configuration.setConfigurationFactory(resolveClass(props.getProperty("configurationFactory")));
    configuration.setShrinkWhitespacesInSql(booleanValueOf(props.getProperty("shrinkWhitespacesInSql"), false));
    configuration.setDefaultSqlProviderType(resolveClass(props.getProperty("defaultSqlProviderType")));
  }

  private void environmentsElement(XNode context) throws Exception {
    if (context != null) {
      if (environment == null) {
        // 获取default属性的值。即需要使用的环境
        environment = context.getStringAttribute("default");
      }
      // 获取子节点。也就是可以配置多个环境，利用上面的default属性指定应该使用哪个属性
      for (XNode child : context.getChildren()) {
        String id = child.getStringAttribute("id");
        // 如果是指定的所需使用的环境。意思是只加载指定的需要使用的环境。其他环境不加载
        if (isSpecifiedEnvironment(id)) {
          // 根据transactionManager标签指定的type类型，获取对应的事务管理员工厂
          TransactionFactory txFactory = transactionManagerElement(child.evalNode("transactionManager"));
          // 根据dataSource标签指定的type，获取数据库工厂
          DataSourceFactory dsFactory = dataSourceElement(child.evalNode("dataSource"));
          // 获取DataSource对象
          DataSource dataSource = dsFactory.getDataSource();
          // 将三个属性封装到环境构建器中
            // 环境的id
          Environment.Builder environmentBuilder = new Environment.Builder(id)
            // 使用的事务工厂
              .transactionFactory(txFactory)
          // 使用的数据库
              .dataSource(dataSource);
          // 构建环境，并保存到configuration对象中。体现的是建造者模式，构建完成后，环境对象就不再能改变
          configuration.setEnvironment(environmentBuilder.build());
          break;
        }
      }
    }
  }

  private void databaseIdProviderElement(XNode context) throws Exception {
    DatabaseIdProvider databaseIdProvider = null;
    if (context != null) {
      String type = context.getStringAttribute("type");
      // awful patch to keep backward compatibility
      // 保持向后兼容性的糟糕补丁
      if ("VENDOR".equals(type)) {
        type = "DB_VENDOR";
      }
      Properties properties = context.getChildrenAsProperties();
      databaseIdProvider = (DatabaseIdProvider) resolveClass(type).getDeclaredConstructor().newInstance();
      databaseIdProvider.setProperties(properties);
    }
    Environment environment = configuration.getEnvironment();
    if (environment != null && databaseIdProvider != null) {
      String databaseId = databaseIdProvider.getDatabaseId(environment.getDataSource());
      configuration.setDatabaseId(databaseId);
    }
  }

  private TransactionFactory transactionManagerElement(XNode context) throws Exception {
    if (context != null) {
      // 获取type属性
      String type = context.getStringAttribute("type");
      // 获取子节点的内容
      Properties props = context.getChildrenAsProperties();
      // 实例化事务管理工厂
      TransactionFactory factory = (TransactionFactory) resolveClass(type).getDeclaredConstructor().newInstance();
      // 为事务管理工厂配置值
      factory.setProperties(props);
      return factory;
    }
    //  如果没有指定事务管理员，则报错
    throw new BuilderException("Environment declaration requires a TransactionFactory.");
  }

  private DataSourceFactory dataSourceElement(XNode context) throws Exception {
    if (context != null) {
      String type = context.getStringAttribute("type");
      // 获取子节点的内容。比如url，username，password等
      Properties props = context.getChildrenAsProperties();
      // 到这一步，DataSource就已经new出来了
      DataSourceFactory factory = (DataSourceFactory) resolveClass(type).getDeclaredConstructor().newInstance();
      // 配置数据库工厂，例如将数据库的用户名密码等设置到DataSource里去
      factory.setProperties(props);
      return factory;
    }
    throw new BuilderException("Environment declaration requires a DataSourceFactory.");
  }
  // 自定义的类型处理器
  private void typeHandlerElement(XNode parent) {
    if (parent != null) {
      for (XNode child : parent.getChildren()) {
        if ("package".equals(child.getName())) {
          String typeHandlerPackage = child.getStringAttribute("name");
          typeHandlerRegistry.register(typeHandlerPackage);
        } else {
          String javaTypeName = child.getStringAttribute("javaType");
          String jdbcTypeName = child.getStringAttribute("jdbcType");
          String handlerTypeName = child.getStringAttribute("handler");
          Class<?> javaTypeClass = resolveClass(javaTypeName);
          JdbcType jdbcType = resolveJdbcType(jdbcTypeName);
          Class<?> typeHandlerClass = resolveClass(handlerTypeName);
          if (javaTypeClass != null) {
            if (jdbcType == null) {
              typeHandlerRegistry.register(javaTypeClass, typeHandlerClass);
            } else {
              typeHandlerRegistry.register(javaTypeClass, jdbcType, typeHandlerClass);
            }
          } else {
            typeHandlerRegistry.register(typeHandlerClass);
          }
        }
      }
    }
  }

  private void mapperElement(XNode parent) throws Exception {
    if (parent != null) {
      // 遍历处理子节点。mappers节点下，只能定义mapper和package子节点
      for (XNode child : parent.getChildren()) {
        // 对package子节点的处理
        if ("package".equals(child.getName())) {
          // 获取package子节点的name属性
          String mapperPackage = child.getStringAttribute("name");
          // 根据包名找到所有的接口，并保存
          configuration.addMappers(mapperPackage);
          // 对mapper子节点的处理
        } else {
          // 获取mapper子节点的属性
          String resource = child.getStringAttribute("resource");
          String url = child.getStringAttribute("url");
          String mapperClass = child.getStringAttribute("class");
          // 如果只存在resource属性
          if (resource != null && url == null && mapperClass == null) {
            ErrorContext.instance().resource(resource);
            try(InputStream inputStream = Resources.getResourceAsStream(resource)) {
              XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments());
              mapperParser.parse();
            }
            // 如果只存在url属性
          } else if (resource == null && url != null && mapperClass == null) {
            ErrorContext.instance().resource(url);
            try(InputStream inputStream = Resources.getUrlAsStream(url)){
              XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, url, configuration.getSqlFragments());
              mapperParser.parse();
            }
            // 如果只存在class属性
          } else if (resource == null && url == null && mapperClass != null) {
            Class<?> mapperInterface = Resources.classForName(mapperClass);
            configuration.addMapper(mapperInterface);
            // 如果同时有两个以上的属性，抛出异常。只允许定义一个属性
          } else {
            throw new BuilderException("A mapper element may only specify a url, resource or class, but not more than one.");
          }
        }
      }
    }
  }

  private boolean isSpecifiedEnvironment(String id) {
    if (environment == null) {
      throw new BuilderException("No environment specified.");
    }
    if (id == null) {
      throw new BuilderException("Environment requires an id attribute.");
    }
    return environment.equals(id);
  }

}
